package com.zhm.springboot.controller;

import com.zhm.springboot.domain.UserInfo;
import com.zhm.springboot.service.UserInfoService;
import com.zhm.springboot.utils.EncryptUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by haiming.zhuang on 2016/7/12.
 */
@Controller
public class UserController {
    @Autowired
    private UserInfoService userInfoService;
//    @PreAuthorize("hasAuthority('/user/list')")
    @RequestMapping(value="/user/list",method = RequestMethod.GET)
    public String list(ModelMap model){
        List<UserInfo> results = userInfoService.findAll();
        model.addAttribute("results",results);
        return "user/list";
    }
    @PreAuthorize("hasAuthority('/user/list/rest')")
    @RequestMapping(value="/user/list/rest",method = RequestMethod.GET)
    public @ResponseBody List<UserInfo> listRest(){
        List<UserInfo> results = userInfoService.findAll();
        return results;
    }
    @PreAuthorize("hasAuthority('/user/add')")
    @RequestMapping(value = "/user/add",method = RequestMethod.GET)
    public String add(){
        return "user/add";
    }
    @PreAuthorize("hasAuthority('/user/mod')")
    @RequestMapping(value = "/user/mod",method = RequestMethod.GET)
    public String mod(Integer userid,ModelMap model){
        UserInfo user = userInfoService.findById(userid);
        model.addAttribute("user",user);
        return "user/mod";
    }
    @PreAuthorize("hasAuthority('/user/del')")
    @RequestMapping(value = "/user/del",method = RequestMethod.POST)
    public @ResponseBody String del(Integer userid){
        userInfoService.delById(userid);
        return "";
    }
    @PreAuthorize("hasAuthority('/user/add')")
    @RequestMapping(value = "/user/add",method = RequestMethod.POST)
    public String formAdd(UserInfo user){
        user.setPassword(EncryptUtils.encodeMD5String("123456"));
        userInfoService.saveUser(user);
        return "redirect:/user/list";
    }
    @PreAuthorize("hasAuthority('/user/mod')")
    @RequestMapping(value = "/user/mod",method = RequestMethod.POST)
    public String formMod(UserInfo user,Integer userid){
        UserInfo dbInfo = userInfoService.findById(userid);
        dbInfo.setIsadmin(user.getIsadmin());
        dbInfo.setUsername(user.getUsername());
        dbInfo.setTelephone(user.getTelephone());
        userInfoService.updateUser(dbInfo);
        return "redirect:/user/list";
    }
}
